<template>
  <body-page>
    <div class="body-page-edit">

      <el-tree :data="treeAllData" :default-checked-keys="treeData" node-key="code"
               :default-expand-all="true"
               :props="treeProps"
               show-checkbox
               @check="handleCheckChange">
      </el-tree>

      <div style="margin-top: 20px; margin-left: 20px;">
        <el-button type="primary" @click="submit"
                   v-if="btnDisplay.treeUpdate">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>

    </div>
  </body-page>
</template>

<script>
import BodyPage from '../../components/BodyPage'
import DictSelect from '../../components/DictSelect'
export default {
  name: 'ApiConfig',
  components: {DictSelect, BodyPage},
  data () {
    return {
      // 根据权限控制按钮显示隐藏
      btnDisplay: {
        treeUpdate: this.$GLOBAL.isUrlPermit(this.$API.fun.treeUpdate)
      },
      treeProps: {
        label: 'name',
        children: 'children'
      },
      treeData: null,
      treeAllData: null,
      apiIdList: null,
      functionId: null
    }
  },
  methods: {
    handleCheckChange (data, allCheckData) {
      // console.log(allCheckData)
      this.apiIdList = []
      for (let index in allCheckData.checkedKeys) {
        if (allCheckData.checkedKeys[index].toString().indexOf('module_') < 0) {
          this.apiIdList.push(allCheckData.checkedKeys[index])
        }
      }
    },

    submit () {
      let vm = this

      // null说明用户没有进行修改
      if (vm.apiIdList === null) {
        vm.$message.success('操作成功')
        vm.cancel()
        return
      }

      this.$axios.post(vm.$API.fun.treeUpdate, vm.$qs.stringify({
        apiCodeList: vm.apiIdList,
        functionCode: vm.functionId
      }, { indices: false })).then(response => {
        if (response.data.code === 2000) {
          vm.$message.success(response.data.message)
          vm.cancel()
        } else {
          vm.$message.error(response.data.message)
        }
      }).catch(response => {
        console.log(response)
        vm.$message.error('系统异常')
      })
    },
    cancel () {
      this.$router.back()
    }
  },
  created () {
    let vm = this

    vm.functionId = vm.$route.query.code

    // 获取接口树
    this.$axios.post(vm.$API.fun.apiTree, vm.$qs.stringify({functionCode: vm.$route.query.code})).then(response => {
      if (response.data.code === 2000) {
        vm.treeData = response.data.data.treeData
        vm.treeAllData = response.data.data.treeAllData
      } else {
        vm.$message.error(response.data.message)
        vm.cancel()
      }
    }).catch(response => {
      console.log(response)
      vm.$message.error('系统异常')
    })
  }
}
</script>

<style scoped>

  .body-page-edit {
    padding: 20px 10px;
    background-color: white;
  }

  .edit-form {
    max-width: 500px;
  }

</style>
